package com.example.mymessagequeue.mqserver;

import com.example.mymessagequeue.common.*;
import com.example.mymessagequeue.mqserver.core.BasicProperties;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 这个 BrokerServer 就是消息队列的本体服务器(基于TCP实现)
 */
public class BrokerServer {
    private ServerSocket serverSocket = null;

    // 当前考虑一个 BrokerServer 上只有一个虚拟主机

    private final VirtualHost virtualHost = new VirtualHost(VirtualHost.DEFAULT_NAME);

    private final Map<String, VirtualHost> virtualHostMap = new ConcurrentHashMap<>();

    // 使用这个 哈希表 表示当前的所有会话(记录当前正在和服务器通信的客户端)
    // key: channelId
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();

    // 使用线程池来处理多个客户端的请求
    private ExecutorService executorService = null;

    // 使用 boolean 变量控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public VirtualHost getVirtualHost(String virtualHostName) {
        return virtualHostMap.get(virtualHostName);
    }

    public void start() throws IOException {
        System.out.println("[BrokerServer] 启动!");
        virtualHostMap.put(VirtualHost.DEFAULT_NAME, virtualHost);
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                // 把处理连接的逻辑丢给线程池
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器停止运行!");
        }

    }

    /**
     * 一般来说停止服务器，就是直接 kill 对应进程就可以了
     * 这里单独的停止方法主要是用于后续的单元测试
     */
    public void stop() throws IOException {
        runnable = false;
        // 把线程池中的任务都放弃了, 让线程都销毁
        executorService.shutdownNow();
        serverSocket.close();
    }

    /**
     * 通过这个方法处理一个客户端的连接
     * 在这一个连接中，可能会涉及到多个请求和响应
     *
     * @param clientSocket
     */
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 这里需要按照特定格式来读取并解析，此时需要用到DataInputStream和DataOutputStream
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    // 1. 读取请求并解析
                    Request request = readRequest(dataInputStream, clientSocket);
                    // 2. 根据请求计算响应
                    Response response = process(request, clientSocket);
                    // 3. 把响应写回给客户端
                    writeResponse(dataOutputStream, response, clientSocket);
                }
            }
        } catch (EOFException | SocketException e) {
            // 对于这个代码, DataInputStream 如果读到 EOF, 就会抛出一个 EOFException 异常
            // 需要借助这个异常来结束循环
            System.out.println("[BrokerServer] connection 关闭! 客户端的地址: " + clientSocket.getInetAddress().toString() +
                    ":" + clientSocket.getPort());
        } catch (IOException | ClassNotFoundException | MqException e) {
            e.printStackTrace();
            System.out.println("[BrokerServer] connection 出现异常!");
        } finally {
            try {
                // 一个 tcp 连接中，可能包含多个 channel，需要把当前这个 socket 对应的所有的 channel 都清理掉
                // 当连接被关闭了, 里面所有的 channel 所对应的消费者应该都取消订阅该队列
                clearClosedSession(clientSocket);
                // 连接处理完了, 记得关闭 socket
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    private Request readRequest(DataInputStream dataInputStream, Socket clientSocket) throws IOException {
        // 如果多线程情况下, 多个线程都针对同一个网络流对象读内容的话, 很容易读混淆, 此时也要考虑线程安全问题
        synchronized (clientSocket.getInputStream()) {
            Request request = new Request();
            request.setType(dataInputStream.readInt());
            request.setLength(dataInputStream.readInt());
            byte[] payload = new byte[request.getLength()];
            int n = dataInputStream.read(payload);
            if (n != request.getLength()) {
                throw new IOException("读取请求格式出错！");
            }
            request.setPayload(payload);
            return request;
        }
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response, Socket socket) throws IOException {
        // 如果队列中有很多消息，多线程同时响应给客户端的时候，这里需要考虑线程安全问题
        synchronized (socket.getOutputStream()) {
            dataOutputStream.writeInt(response.getType());
            dataOutputStream.writeInt(response.getLength());
            dataOutputStream.write(response.getPayload());
            // 刷新缓冲区也是重要的操作!
            dataOutputStream.flush();
        }
    }

    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 1. 把 request 汇总的 payload 做一个初步的解析
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[Request] rid=" + basicArguments.getRid() + ", channelId=" + basicArguments.getChannelId() +
                ", type=" + request.getType() + ", length=" + request.getLength());
        // 2. 根据 type 的值, 来进一步区分接下来这次请求要干啥
        boolean ok = true;
        if (request.getType() == 0x1) {
            // 创建 channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建 Channel 成功!");
        } else if (request.getType() == 0x2) {
            // 销毁 channel
            sessions.remove(basicArguments.getChannelId());
            // channel 关闭了, 对应这个 consumerTag(channelId) 也就不在订阅任何队列, 也就是这个消费者下线了
            virtualHost.consumerOffline(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 销毁 Channel 成功！");
        } else if (request.getType() == 0x3) {
            // 创建交换机
            // 先强转成创建交换机方法的参数
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(), arguments.isDurable(),
                    arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x4) {
            // 销毁交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            // 创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(), arguments.isExclusive(),
                    arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            // 销毁队列
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
            // 创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            // 销毁绑定
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            // 发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(), arguments.getBasicProperties(),
                    arguments.getBody());
        } else if (request.getType() == 0xa) {
            // 订阅队列, 消费消息
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(), new Consumer() {
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                    // 这个回调函数要做的, 就是把服务器收到的消息直接推送回对应的消费者客户端
                    // 先要知道这个消息要发送给哪个客户端
                    // 此处的 consumerTag 其实是 channelId, 根据 channelId 去 session 中查询, 就可以得到对应的 socket 对象了
                    // 1. 拿到 socket 对象
                    Socket clientSocket = sessions.get(consumerTag);
                    if (clientSocket == null || clientSocket.isClosed()) {
                        throw new MqException(" [BrokerServer] 订阅消息的客户端已经关闭！");
                    }
                    // 2. 构造响应数据
                    SubScribeReturns subScribeReturns = new SubScribeReturns(); // 消息完整对象
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setRid(""); // 这里只有响应, 没有请求, 不需要去对应响应
                    subScribeReturns.setOk(true);
                    subScribeReturns.setConsumerTag(consumerTag);
                    subScribeReturns.setBody(body);
                    subScribeReturns.setBasicProperties(basicProperties);
                    byte[] payload = BinaryTool.toBytes(subScribeReturns);
                    Response response = new Response();
                    // 0xc 表示服务器给消费者客户端推送的消息数据
                    response.setType(0xc);
                    response.setLength(payload.length);
                    response.setPayload(payload);

                    // 3. 把数据推送给客户端
                    // 这里的 dataOutputStream 不能关闭，如果关闭就会把 clientSocket 里的 outPutStream 也关闭了
                    // 此时就无法继续往 socket 里面写入数据了
                    DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                    writeResponse(dataOutputStream, response, clientSocket);
                }
            });
        } else if (request.getType() == 0xb) {
            // 调用 basicAck 确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        } else {
            // 当前 type 非法
            throw new MqException("[BrokerServer] 未知的请求类型 type=" + request.getType());
        }
        // 3. 构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);

        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid=" + basicReturns.getRid() + ", channelId=" + basicReturns.getChannelId() +
                ", type=" + response.getType() + ", length=" + response.getLength());

        return response;
    }

    // 遍历上述的 sessions 哈希表，把该被管理的 socket 对应的键值对，统统删掉
    private void clearClosedSession(Socket clientSocket) {
        List<String> toDeleteChannelIds = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                // 集合类中不能一边遍历一边删除
                toDeleteChannelIds.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelIds) {
            virtualHost.consumerOffline(channelId);
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理 session 完成! 被清理的 channelId=" + toDeleteChannelIds);
    }

}
